package net.rain.aop;

import net.rain.annotations.AutoInsert;
import net.rain.utils.RainConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * <p>
 * AutoInsertAspect
 * <p>
 *
 * @author 春江花朝秋月夜
 * @since 2023/8/21
 */
@Aspect
@Component
public class AutoInsertAspect {
    @Pointcut("@annotation(net.rain.annotations.AutoInsert)")
    public void autoInsert(){

    }

    //通过反射来获取对象类的方法
    @Before("autoInsert()")
    public void AutoInsert(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Object[] args = joinPoint.getArgs();
        Object o = args[0];

        Method setCreateTime=o.getClass().getDeclaredMethod(RainConstants.SET_CREATE_TIME, LocalDateTime.class);
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();
        AutoInsert insert = signature.getMethod().getAnnotation(AutoInsert.class);
        String value = insert.value();
        if (value.equals(RainConstants.INSERT)){
            setCreateTime.invoke(o,LocalDateTime.now());
        }
    }
}
